<?php declare(strict_types=1);

namespace App\Api\V2\Controller\Bill\User;


use App\Api\Controllers\BaseController;
use App\Exceptions\BizException;
use App\Models\Store;
use App\Models\User;
use App\Services\Count\FinanceCountService;
use App\Services\Count\UserBillCountService;
use App\Services\Count\UserService;
use App\Services\PrintSqlService;
use App\Traits\ResponseTrait;
use App\Util\TimeUtil;
use Illuminate\Http\Request;

class FinanceController extends BaseController
{

    use ResponseTrait;

    const MARK = [
        101 => 1,
        747 => 4,
        874 => 5,
        1002 => 6
    ];

    public function markUser(): string
    {
        $user = User::query()->select(["id", "name"])->whereIn("id", array_keys(self::MARK))->get();
        return $this->successResponse("ok", [
            "data" => $user->toArray()
        ]);
    }

    //财务月账单统计
    public function financeMonthCount(Request $request): string
    {
        try {
            $startDate = $request->get("startDate", date("Y-m-d" . " 00:00:00", time()));
            $endDate = $request->get("endDate", date("Y-m-d" . " 23:59:59", time()));
            if (date("Ym", strtotime($startDate)) != date("Ym", strtotime($endDate))) {
                throw new \Exception("不能跨月查询");
            }
            $month = date("Ym", strtotime($startDate));
            $mark = $request->get("mark", 0);
            if ($mark == 1) {
                $agent_id = $request->get("agent_id", 0);
                if (empty($agent_id)) {
                    throw new BizException("请选择打标代理商");
                }
                $store = Store::query()->where("ascription", self::MARK[$agent_id] ?? 0)->get();
                list($oem_id, $agent1_id, $agent2_id, $agent3_id, $agent4_id) = [0, 0, 0, 0, 0];
                $storeIds = $storePid = [];
                foreach ($store as $val) {
                    $storePid[] = $val->store_id;
                }
            } else {
                $agent1_id = $agent2_id = $agent3_id = $agent4_id = 0;
                $agent_id = $request->get("agent_id", 0);
                if (!empty($agent_id)) {
                    $userLists = (new UserService())->userPrev((int)$agent_id);
                    $userLists = array_reverse($userLists);
                    $agent1_id = $userLists[1]["id"] ?? 0;
                    $agent2_id = $userLists[2]["id"] ?? 0;
                    $agent3_id = $userLists[3]["id"] ?? 0;
                    $agent4_id = $userLists[4]["id"] ?? 0;
                }
                $storeId = $request->get("store_id");
                $storeIds = [];
                $storePid = "";
                if (!empty($storeId)) {
                    $store = Store::query()->where("store_id", $storeId)->first();
                    if (empty($store)) {
                        throw new \Exception("店铺不存在");
                    }
                    if ($store->pid == 0) {
                        $storePid = $store->store_id;
                    } else {
                        $storeP = Store::query()->where("id", $store->pid)->first();
                        $storePid = $storeP->store_id;
                    }
                    $storeIdSub = Store::query()->where("pid", $store->id)->pluck("store_id")->toArray();
                    $storeIds = array_merge([$storeId], $storeIdSub);
                }
            }
//            $month = $request->get("month", date("Ym", time()));
//            $util = new TimeUtil();
//            list($startDate, $endDate) = $util->getMonthRange((string)$month . "01 00:00:00");


            $where = [
                "month" => $month,
                "store_pid" => $storePid,
                "store_id" => $storeIds,
                "receive_model" => $request->get("receive_model", 0),
                "agent1_id" => $agent1_id,
                "agent2_id" => $agent2_id,
                "agent3_id" => $agent3_id,
                "agent4_id" => $agent4_id,
                "company" => $request->get("company", ""),
                "startDate" => $startDate,
                "endDate" => $endDate,
                "mch_no" => $request->get("mch_no", ""),
                "page" => $request->get("page", 1),
                "pagesize" => $request->get("pagesize", 20)
            ];
            $service = new FinanceCountService();
            $data = $service->financeMonthCount($where);

            return $this->successResponse("ok", $data);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }


    public function financeMonthCountExport(Request $request): string
    {
        try {

            $startDate = $request->get("startDate", date("Y-m-d" . " 00:00:00", time()));
            $endDate = $request->get("endDate", date("Y-m-d" . " 23:59:59", time()));
            if (date("Ym", strtotime($startDate)) != date("Ym", strtotime($endDate))) {
                throw new \Exception("不能跨月查询");
            }
            $month = date("Ym", strtotime($startDate));

            $mark = $request->get("mark", 0);

            if ($mark == 1) {
                $agent_id = $request->get("agent_id", 0);
                if (empty($agent_id)) {
                    throw new BizException("请选择打标代理商");
                }
                $store = Store::query()->where("ascription", self::MARK[$agent_id] ?? 0)->get();
                $storeIds = $storePid = [];
                foreach ($store as $val) {
                    $storePid[] = $val->store_id;
                }
            } else {
                $agent1_id = $agent2_id = $agent3_id = $agent4_id = 0;
                $agent_id = $request->get("agent_id", 0);
                if (!empty($agent_id)) {
                    $userLists = (new UserService())->userPrev((int)$agent_id);
                    $userLists = array_reverse($userLists);
                    $agent1_id = $userLists[1]["id"] ?? 0;
                    $agent2_id = $userLists[2]["id"] ?? 0;
                    $agent3_id = $userLists[3]["id"] ?? 0;
                    $agent4_id = $userLists[4]["id"] ?? 0;
                }
                $storeId = $request->get("store_id");
                $storeIds = [];
                $storePid = "";
                if (!empty($storeId)) {
                    $store = Store::query()->where("store_id", $storeId)->first();
                    if (empty($store)) {
                        throw new \Exception("店铺不存在");
                    }
                    if ($store->pid == 0) {
                        $storePid = $store->store_id;
                    } else {
                        $storeP = Store::query()->where("id", $store->pid)->first();
                        $storePid = $storeP->store_id;
                    }
                    $storeIdSub = Store::query()->where("pid", $store->id)->pluck("store_id")->toArray();
                    $storeIds = array_merge([$storeId], $storeIdSub);
                }
            }
            $where = [
                "month" => $month,
                "store_pid" => $storePid,
                "store_id" => $storeIds,
                "receive_model" => $request->get("receive_model", 0),
                "agent1_id" => $agent1_id,
                "agent2_id" => $agent2_id,
                "agent3_id" => $agent3_id,
                "agent4_id" => $agent4_id,
                "company" => $request->get("company", ""),
                "startDate" => $startDate,
                "endDate" => $endDate,
                "mch_no" => $request->get("mch_no", ""),
                "page" => $request->get("page", 1),
                "pagesize" => $request->get("pagesize", 20)
            ];

            $service = new FinanceCountService();

            $data = $service->financeMonthCountExport($where);

            return $this->successResponse("ok", ["data" => $data]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage().$e->getLine().$e->getFile());
        }
    }


    //财务日账单统计
    public function staticBillLogList(Request $request): string
    {
        try {
            $user = $this->parseToken();
            $mark = $request->get("mark", 0);
            $agent_id = $user->user_id;  //查找下级所有的数据
            if (!empty($request->get("agent1_id"))) {
                $agent_id = $request->get("agent1_id");
            }
            if (!empty($request->get("agent2_id"))) {
                $agent_id = $request->get("agent2_id");
            }
            if (!empty($request->get("agent3_id"))) {
                $agent_id = $request->get("agent3_id");
            }
            if (!empty($request->get("agent4_id"))) {
                $agent_id = $request->get("agent4_id");
            }
            if (!empty($request->get("agent_id"))) {
                $agent_id = $request->get("agent_id", 0);
            }
            if ($mark == 1) {
                $fee_column = "agent1_fee";
                if (empty($agent_id)) {
                    throw new BizException("请选择打标代理商");
                }
                $store = Store::query()->where("ascription", self::MARK[$agent_id] ?? 0)->get();
                list($oem_id, $agent1_id, $agent2_id, $agent3_id, $agent4_id) = [0, 0, 0, 0, 0];
                $storeId = $storePid = [];
                foreach ($store as $val) {
                    $storePid[] = $val->store_id;
                }
            } else {
                $userService = new UserService();
                list($idValues, $column) = $userService->handleUserAccountRelation((int)$agent_id);
                list($oem_id, $agent1_id, $agent2_id, $agent3_id, $agent4_id) = $idValues;
                list($profit_column, $fee_column) = $column;
                if ($agent_id == 1) {
                    $fee_column = "oem_fee";
                } else {
                    $fee_column = "agent1_fee";
                }
                $storePid = $request->get("store_pid");
                $storeId = $request->get("store_id");
            }

            $startDate = $request->get("startDate", date("Y-m-d" . " 00:00:00", time()));
            $endDate = $request->get("endDate", date("Y-m-d" . " 23:59:59", time()));
            if (date("Ym", strtotime($startDate)) != date("Ym", strtotime($endDate))) {
                throw new \Exception("不能跨月查询");
            }

            $where = [
                "oem_id" => $oem_id,
                "agent1_id" => $agent1_id,
                "agent2_id" => $agent2_id,
                "agent3_id" => $agent3_id,
                "agent4_id" => $agent4_id,
//                "profit_column" => $profit_column,
                "fee_column" => $fee_column,
                "page" => $request->get("page", 1),
                "pagesize" => $request->get("pagesize", 20),
                "store_pid" => $storePid,
                "store_id" => $storeId,
                "curHdIndex" => 0,
                "startDate" => $startDate,
                "endDate" => $endDate,
                "mch_no" => $request->get("mch_no", ""),
//                "pay_type" => $request->get("pay_type"),
                "company" => $request->get("company"),
                "receive_model" => $request->get("receive_model"),
                "rate" => (float)$request->get("pay_rate"),
                "agent1_rate" => (float)$request->get("agent_rate")
            ];
//            PrintSqlService::listen();
            //在这里统计店铺
            $service = new FinanceCountService();
            list($list, $total) = $service->staticBillLogList($where);
            return $this->successResponse("ok", ["data" => $list, "total" => $total]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }


    public function staticBillLogListExport(Request $request): string
    {
        try {
            $user = $this->parseToken();

            $mark = $request->get("mark", 0);

            $agent_id = $user->user_id;  //查找下级所有的数据
            if (!empty($request->get("agent1_id"))) {
                $agent_id = $request->get("agent1_id");
            }
            if (!empty($request->get("agent2_id"))) {
                $agent_id = $request->get("agent2_id");
            }
            if (!empty($request->get("agent3_id"))) {
                $agent_id = $request->get("agent3_id");
            }

            if (!empty($request->get("agent4_id"))) {
                $agent_id = $request->get("agent4_id");
            }

            if (!empty($request->get("agent_id"))) {
                $agent_id = $request->get("agent_id", 0);
            }

            if ($mark == 1) {
                $fee_column = "agent1_fee";
                if (empty($agent_id)) {
                    throw new BizException("请选择打标代理商");
                }
                $store = Store::query()->where("ascription", self::MARK[$agent_id] ?? 0)->get();
                list($oem_id, $agent1_id, $agent2_id, $agent3_id, $agent4_id) = [0, 0, 0, 0, 0];
                $storeId = $storePid = [];
                foreach ($store as $val) {
                    $storePid[] = $val->store_id;
                }
            } else {
                $userService = new UserService();
                list($idValues, $column) = $userService->handleUserAccountRelation((int)$agent_id);
                list($oem_id, $agent1_id, $agent2_id, $agent3_id, $agent4_id) = $idValues;
                list($profit_column, $fee_column) = $column;
                if ($agent_id == 1) {
                    $fee_column = "oem_fee";
                } else {
                    $fee_column = "agent1_fee";
                }
                $storePid = $request->get("store_pid");
                $storeId = $request->get("store_id");
            }


            $startDate = $request->get("startDate", date("Y-m-d" . " 00:00:00", time()));
            $endDate = $request->get("endDate", date("Y-m-d" . " 23:59:59", time()));
            if (date("Ym", strtotime($startDate)) != date("Ym", strtotime($endDate))) {
                throw new \Exception("不能跨月查询");
            }

            $where = [
                "oem_id" => $oem_id,
                "agent1_id" => $agent1_id,
                "agent2_id" => $agent2_id,
                "agent3_id" => $agent3_id,
                "agent4_id" => $agent4_id,
//                "profit_column" => $profit_column,
                "fee_column" => $fee_column,
                "store_pid" => $storePid,
                "store_id" => $storeId,
                "curHdIndex" => 0,
                "startDate" => $startDate,
                "endDate" => $endDate,
                "mch_no" => $request->get("mch_no", ""),
//                "pay_type" => $request->get("pay_type"),
                "company" => $request->get("company"),
                "receive_model" => $request->get("receive_model"),
                "rate" => (float)$request->get("pay_rate"),
                "agent1_rate" => (float)$request->get("agent_rate")
            ];
            //在这里统计店铺
            $countService = new FinanceCountService();
            $url = $countService->staticBillLogListExport($where);
            return $this->successResponse("ok", ["data" => $url]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }


}